<script setup>
import router from "@/router";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {getCaptcharService} from "@/api/captcha";
import {user} from "@/stores/counter.js";

const isLoading=ref(false);

const formData = ref({
  username: "",
  password: "",
  code: "",
  token: "",
});

const imageUrl = ref("");

function goToRegister() {
  router.push("/register");
}

const checkForm = () => {
  if (formData.value.username === "" || formData.value.password === "") {
    ElMessage.error("用户名或密码不能为空");
    return false;
  } else if (formData.value.code === "") {
    ElMessage.error("验证码不为空");
    return false;
  }
  return true;
}

const getCode = async () => {
  let result = await getCaptcharService();
  console.log(result);
  imageUrl.value = "data:image/gif;base64," + result.data.base64Img;
  console.log(imageUrl.value);
  formData.value.token = result.data.token;
};
const userStore = user();
const login = async () => {
  if(!checkForm()){return;}
  console.log("loginData", formData.value);

  isLoading.value=true;

  userStore.login(formData.value).then((res) => {
    ElMessage.success(res.data);
    isLoading.value=false;
    router.push("/index");
  }).catch((err) => {
    isLoading.value=false;
    ElMessage.error(err);
  });
};

onMounted(async () => {
  await getCode();
});
</script>

<template>

  <!-- 总容器 -->
  <div class="wrapper" v-loading="isLoading">

    <h1 style="margin-bottom: 5vh">体检预约-登录</h1>
    <section>
      <div class="input-box">
        <i class="fa fa-user-o"></i>
        <input type="text" placeholder="请输入用户名" v-model="formData.username">
      </div>
      <div class="input-box">
        <i class="fa fa-lock"></i>
        <input type="password" placeholder="请输入登录密码" v-model="formData.password">
      </div>
      <div class="input-box">
        <i class="fa fa-lock"></i>
        <input type="text" placeholder="请输入验证码" v-model="formData.code">
      </div>
      <img :src="imageUrl" class="code-image" @click="getCode" alt="验证码"/>
      <div class="reg-box">
        <p @click="goToRegister">注册</p>
        <p>忘记密码？</p>
      </div>
      <div class="button-box" @click="login">登录</div>
    </section>

    <footer>
      <div>
        <div class="line"></div>
        <p>有疑问请联系客服</p>
        <div class="line"></div>
      </div>
      <p>4008-XXX-XXX</p>
    </footer>
  </div>

</template>

<style scoped>
@import "@/assets/css/login.css";
@import "@/assets/framework/font-awesome/css/font-awesome.min.css";
@import "@/assets/framework/reset.css";


.wrapper {
  width: 100vw;
  height: 100vh;
  padding-top: 15vh;
}

.code-image {
  scale: 80%;
  position: relative;
  transform: translate(-3vw,0);
  margin-top: 2vh;
}

</style>
